<?php

class ConditionParser {
    private $expression;

    public function __construct($expression) {

        $this->expression = str_replace(' ','',$expression);
    }

    public function parse() {
        $tokens = $this->tokenize($this->expression);
        $ast = $this->parseExpression($tokens);
        return $ast;
    }

    private function tokenize($expression) {
        $tokens = [];
        $pattern = '/(\d+|==|!=|>=|<=|&&|\|\||\(|\)|[^=!|&<>()]+)/';
        preg_match_all($pattern, $expression, $matches);
        print_r($matches);
        foreach ($matches[0] as $match) {
            if (trim($match) !== '') {
                $tokens[] = $match;
            }
        }
        print_r($tokens);
        return $tokens;
    }

    private function parseExpression(&$tokens) {
        $left = $this->parseTerm($tokens);

        while (isset($tokens[0]) && $tokens[0] === '&&') {
            array_shift($tokens);
            $right = $this->parseTerm($tokens);
            $left = ['type' => 'binary', 'operator' => '&&', 'left' => $left, 'right' => $right];
        }

        return $left;
    }

    private function parseTerm(&$tokens) {
        $left = $this->parseFactor($tokens);

        while (isset($tokens[0]) && $tokens[0] === '||') {
            array_shift($tokens);
            $right = $this->parseFactor($tokens);
            $left = ['type' => 'binary', 'operator' => '||', 'left' => $left, 'right' => $right];
        }

        return $left;
    }

    private function parseFactor(&$tokens) {
        $token = array_shift($tokens);

        if ($token === '(') {
            $expression = $this->parseExpression($tokens);
            array_shift($tokens); // Remove ')'
            return $expression;
        }

        return $this->parseComparison($token, $tokens);
    }

    private function parseComparison($left, &$tokens) {
        $operator = array_shift($tokens);
        $right = array_shift($tokens);

        return [
            'type' => 'comparison',
            'operator' => $operator,
            'left' => $left,
            'right' => $right
        ];
    }
}

// Example usage
$expression = '%QQ%!=%主人% && (%QQ%!=2986724176 || 1==turn) ';
$parser = new ConditionParser($expression);
$ast = $parser->parse();
print_r($ast);

?>